// pages/confirmOrder/confirmOrder.js
var core = require("../../utils/core.js");
var WxParse = require('../../libs/wxParse/wxParse.js');
import Toast from '../../components/dist/toast/toast';
import Notify from '../../components/dist/notify/notify';
const app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {

    shequData: '', //社区信息
    goodsInfo: [], //商品信息
    show: false,
    phoneNum: '', //用户手机号，默认为空
    userName: '', //用户名称
    totalMoney: '', //总额
    DiscountNum: '', //优惠钱数
    TotalSum: '', //合计
    type: '', //跳转过来的页面类型
    sureOrder: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    var type = options.type;
    var that = this;
    that.setData({
      type: type
    })
    wx.getStorage({ //获取商品信息
      key: 'goodsInfo',
      success: function(res) {
        console.log(res.data)
        if (type == 'detail') {
          console.log('detail传过来的')
          var obj = {};
          // obj.id = res.data.id
          obj.thumb = res.data.thumb
          obj.groupprice = res.data.groupprice
          obj.total = res.data.total
          obj.selected = res.data.selected
          obj.all_total = res.data.all_total
          obj.goodsid = res.data.id
          obj.title = res.data.title
          that.setData({
            goodsInfo: [obj]
          })
        } else if (type == 'cart') {
          console.log('cart传过来的')
          that.setData({
            goodsInfo: res.data
          })
        }

      },
    })

    wx.getStorage({
      key: 'choosedSheQu',
      success: function(res) {
        console.log(res)
        that.setData({
          shequData: res.data
        })

      },
      fail: function() {
        console.log('获取社区信息失败');
      }
    })

    wx.getStorage({
      key: 'Userphone',
      success: function(res) {
        console.log(res)
        console.log('获取到手机号码了')
        that.setData({
          phoneNum: res.data,
          show: false
        })
      },
      fail: function() {
        console.log('没获取到手机号码');
        that.setData({
          phoneNum: '',
          show: true
        })
      }
    })
  },
  cacanelSq: function() {
    this.setData({
      show: false
    })
    Notify('请手动输入收货手机号码')
  },
  getPhoneNumber: function(e) { //获取手机号
    var that = this;
    console.log(JSON.stringify(e));
    // console.log(e.detail.errMsg)
    // console.log(e.detail.iv)
    // console.log(e.detail.encryptedData)
    wx.getStorage({
      key: 'sessionKey',
      success: function(res) {
        console.log('sessionKey获取成功')
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
          console.log('ok');
          core.get("wxapp/getWxMobile", {
            'data': e.detail.encryptedData,
            'iv': e.detail.iv,
            'sessionKey': res.data
          }, function(e) {
            console.log(e)
            that.setData({
              phoneNum: e.phoneNumber,
              show: false
            })
            wx.setStorage({
              key: 'Userphone',
              data: e.phoneNumber,
            })
          })
        } else {
          console.log('失败');
          that.setData({
            phoneNum: '',
            show: false
          })
          Notify('请手动输入收货手机号码')

        }
      },
      fail: function() {
        that.setData({
          phoneNum: '',
          show: false
        })
        console.log('sessionKey获取失败还没登录');
        getApp().getUserInfo()
      }
    })
  },
  caculatePrice: function() { //计算总价，优惠等
    //totalMoney: '',//总额
    //DiscountNum: '',//优惠钱数
    //TotalSum: '',//合计优惠后的
    var goodsInfo = this.data.goodsInfo;
    var totalMoney = 0.00;
    var DiscountNum = 0.00;
    var TotalSum = 0.00;
    for (var i = 0; i < goodsInfo.length; i++) {
      totalMoney += parseInt(goodsInfo[i].total) * parseFloat(goodsInfo[i].groupprice)
    }
    console.log(totalMoney);
    TotalSum = totalMoney - DiscountNum;
    this.setData({
      totalMoney: totalMoney,
      DiscountNum: DiscountNum,
      TotalSum: TotalSum
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    // this.onLoad()
    setTimeout(function() {
      that.caculatePrice();

    }, 100)
    console.log(app.getCache("userinfo"))
    var userInfo = app.getCache("userinfo")
    that.setData({
      userName: userInfo.nickName
    })

  },
  submitbtn: function() {
    this.setData({
      sureOrder: true
    })
  },
  sureToPayOrder: function() {
    this.createOrder();
  },
  createOrder: function() {
    var that = this;
    var d = {};
    d.goods = that.data.goodsInfo;
    d.cap_id = that.data.shequData.id;
    d.name = that.data.userName;
    d.mobile = that.data.phoneNum;
    core.post("groupapp/order/create", d, function(t) {
      console.log(t)
      if (0 == t.error) {
        that.goToPay(t.orderid);
      } else {
        Toast(t.message);
      }

    })

  },
  goToPay: function(e) { //调支付
    console.log(e);
    var that = this;
    var t = this;
    var obj = {};
    obj.id = e;
    core.get("groupapp/order/pay", obj, function(o) {
      // console.log('get_list得到的:' + JSON.stringify(o))
      if (50018 != o.error) {
        (!o.wechat.success && "0.00" != o.order.price && o.wechat.payinfo && e.alert(o.wechat.payinfo.message + "\n不能使用微信支付!"),
          t.setData({
            Paylist: o,
          }))
        t.weChat(e);

      } else {
        wx.navigateTo({
          url: "/pages/order/details/index?id=" + e
        });
      };
    });
  },
  weChat: function(id) {
    // console.log('weChat');
    // console.log(JSON.stringify(this.data.Paylist));
    var o = '';
    var a = this;
    var i = this.data.Paylist.wechat
    if (this.data.Paylist.order.price == 0) {
      console.log('价格为0');
      o = "credit";
      a.complete(o, id);
    } else {
      o = "wechat";
      core.pay(i.payinfo, function(t) {
        console.log(JSON.stringify(t));
        "requestPayment:ok" == t.errMsg && a.complete(o, id);
      })
    }


  },
  complete: function(t, id) {
    console.log('comolete:传过来的' + JSON.stringify(t));
    var a = this;
    core.post("order/pay/complete", {
      id: id,
      type: t
    }, function(t) {
      console.log('支付成功返回值' + JSON.stringify(t));
      if (0 == t.error) {
        t.buyTypse = a.data.buyTypse;
        wx.setStorage({
          key: 'payRes',
          data: t,
        })
        wx.navigateTo({
          url: "/pages/order/pay/index?id=" + JSON.stringify(t)
        })
        // return a.setData({
        //   success: !0,
        //   successData: t,
        //   order: t.order,
        //   ordervirtual: t.ordervirtual,
        //   ordervirtualtype: e
        // }), void console.log(t.ordervirtual);
      }
      // o.toast(a, t.message);
    }, !0, !0);
  },

  onClose() {
    this.setData({
      sureOrder: false
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})